﻿using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using PHMEE.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;

namespace PHMEE
{
    public class FleetManager : DomainService, IFleetManager
    {
        private readonly IStringLocalizer<PHMEEResource> L;
        private readonly IFleetRepository fleetRepository;
        private readonly ICompanyRepository companyRepository;

        public FleetManager(IStringLocalizer<PHMEEResource> L, IFleetRepository fleetRepository, ICompanyRepository companyRepository)
        {
            this.L = L;
            this.fleetRepository = fleetRepository;
            this.companyRepository = companyRepository;
        }

        public async Task<Fleet> CreateFleet(Guid companyId, string name)
        {
            var existingFleet = await fleetRepository.FirstOrDefaultAsync(item => item.CompanyId == companyId && item.Name == name);
            if (existingFleet != null)
            {
                throw new UserFriendlyException(L[PHMEEDomainErrorCodes.FleetNameAlreadyExist], PHMEEDomainErrorCodes.FleetNameAlreadyExist).WithData("Name", name);
            }
            var id = GuidGenerator.Create();
            return new Fleet(id, name, companyId);
        }

        public async Task<Dictionary<Guid, Company>> GetCompaniesByFleetIdsAsync(IEnumerable<Guid> fleetIds)
        {
            Dictionary<Guid, Company> result = new Dictionary<Guid, Company>();
            var fleets = await fleetRepository.GetListAsync(item => fleetIds.Contains(item.Id));
            var companyIds = fleets.Select(item => item.CompanyId).Distinct().ToList();
            var companies = await companyRepository.GetListAsync(item => companyIds.Contains(item.Id));
            foreach (var fleet in fleets)
            {
                var company = companies.FirstOrDefault(item => item.Id == fleet.CompanyId);
                if (company != null)
                {
                    result.Add(fleet.Id, company);
                }
            }
            return result;
        }

    }
}
